package ssi.actions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ssi.beans.User;
import ssi.tools.Connector;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class LoginAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		HttpSession session;
		String target = null;
		User loginForm = (User) form;
		String login = loginForm.getUserName();
		String password = DigestUtils.md5Hex(loginForm.getPassword());
		ActionErrors actionErrors = new ActionErrors();
		
		
		if(!(login==null || login.equals(""))){
		

		try {
			Connection connection = new Connector().getConnection();
			Statement statement = connection.createStatement();
			ResultSet result = statement
					.executeQuery("SELECT email, password, type, name, surname, activation, id, address FROM `users` WHERE email=\""
							+ login + "\" && password=\"" + password + "\" LIMIT 1");
			if (result.next()) {

				if (result.getString(6).equals("")) {
					session = request.getSession(true);
					session.setAttribute("user",
							new User(result.getInt(7), result.getString(1),
									result.getString(2), result.getString(3),
									result.getString(4), result.getString(5),
									result.getString(8)));
					target = "success";
					result.close();
					connection.close();
				} else {
					actionErrors.add("info",
							new ActionMessage("error.activation"));
					target = "failure";
					result.close();
					connection.close();

				}
			} else {

				target = "failure";

				actionErrors.add("info",
						new ActionMessage("error.password"));
				result.close();
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		}else{
			//asdasd
			actionErrors.add("info",
					new ActionMessage("error.emptyemail"));
		}
		
		if(actionErrors.size() !=0){
			extracted(request, actionErrors);
			return new ActionForward(mapping.getInput());
		}
		return mapping.findForward(target);

	}

	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}
}